package com.jukte.recipe;

import java.util.List;
import com.ewhat.recipes.R;
import com.jukte.recipe.db.DataBaseManager;
import com.jukte.recipe.models.Direction;
import com.jukte.recipe.models.IngGroup;
import com.jukte.recipe.models.Ingredient;
import com.jukte.recipe.models.Note;
import com.jukte.recipe.models.Recipe;
import com.jukte.recipe.models.Tips;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class RecipeDetailsActivity extends BaseActivity implements OnClickListener{

	private TextView nameTxt, descriptionTxt, servesTxt;
	private ImageView image,addNotesBtn;
	private int recipeId;
	private Recipe recipe;
	private ProgressDialog m_ProgressDialog;
	private Context context;
	private LinearLayout ingredientPanel,directionPanel,notesPanel,tipsPanel;
	private LayoutInflater inflater;
	private ImageView addFavBtn,addToCartBtn;
	private int favValue;
	private View tipsPanelDivider;
	private String noteToInsert,recipeName;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_recipe_details);
		getIntentData();
		
		init();
		
		fetchRecipeDataByDeep();
		
	}
	
	private void getIntentData() {
		recipeId = getIntent().getIntExtra("RECIPE_ID", 0);
		recipeName = getIntent().getStringExtra("RECIPE_NAME");
	}
	
	@Override
	public void init() {
		super.init();
		tv_title.setText(recipeName);

		
		context=RecipeDetailsActivity.this;
		inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		nameTxt = (TextView) findViewById(R.id.name_txt);
		descriptionTxt = (TextView) findViewById(R.id.description_txt);
		servesTxt = (TextView) findViewById(R.id.serves_txt);
		image = (ImageView) findViewById(R.id.image);
		ingredientPanel=(LinearLayout)findViewById(R.id.ing_panel);
		directionPanel=(LinearLayout)findViewById(R.id.direction_panel);
		addFavBtn=(ImageView)findViewById(R.id.fav_btn);
		addToCartBtn=(ImageView)findViewById(R.id.addtocart_btn);
		addFavBtn.setOnClickListener(this);
		addToCartBtn.setOnClickListener(this);
		notesPanel=(LinearLayout)findViewById(R.id.notes_panel);
		tipsPanel=(LinearLayout)findViewById(R.id.tips_panel);
		tipsPanelDivider=(View)findViewById(R.id.tips_panel_divider);
		addNotesBtn=(ImageView)findViewById(R.id.add_note_btn);
		addNotesBtn.setOnClickListener(this);
	}
	
	private void fetchRecipeDataByDeep() {
		Thread thread = new Thread(null, dbFetch, "MagentoBackground");
		thread.start();
		m_ProgressDialog = ProgressDialog.show(this, "", "Fetching data...",
				true);
		m_ProgressDialog.setCancelable(true);
	}

	Runnable dbFetch = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			getRecipeFromDb();
			runOnUiThread(returnRecipeData);
		}

		
	};
	Runnable returnRecipeData = new Runnable() {

		@Override
		public void run() {
			m_ProgressDialog.dismiss();
			updateUi();

		}

		
	};

	private void updateUi() {
		String name=recipe.getName();
		if(name!=null)
		{
			nameTxt.setText(name);
			setTitle("I Love Quinoa");
		}
		else
			nameTxt.setVisibility(View.GONE);
		
		
		String description=recipe.getDescription();
		if(description==null || description.equalsIgnoreCase(""))
			descriptionTxt.setVisibility(View.GONE);
		else 
			descriptionTxt.setText(description);
		
		
		String serves=recipe.getServes();
		if(serves==null || serves.equalsIgnoreCase(""))
			servesTxt.setVisibility(View.GONE);
		else
			servesTxt.setText("Serves: "+serves);
		
		
		String imgPath=recipe.getImgPath();
		if(imgPath!=null){
		    Bitmap bmp = BitmapFactory.decodeFile(context.getFilesDir().getPath()+"/raw/"+imgPath);
		    
			if(null != bmp){
				image.setImageBitmap(bmp);
			}
			else{
				image.setVisibility(View.GONE);
			}
		}
		else
		{
			image.setVisibility(View.GONE);
		}
		favValue=recipe.getIsFav();
		updateFavBtnState(favValue);
		updateIngredientPanel();
		updateDirectionPanel();
		updateNotesPanel();
		updateTipsPanel();
		updatePdfPanel();
	}
	
	private void updatePdfPanel() {
		// TODO Auto-generated method stub
		/*if(recipe.getHasPdf()==1)
		{
			pdfpanel.setVisibility(View.VISIBLE);
			
		}
		else
			pdfpanel.setVisibility(View.GONE);*/
	}

	private void updateFavBtnState(int isFav) {
		// TODO Auto-generated method stub
		if(isFav==0)
		{
			addFavBtn.setImageResource(R.drawable.ic_star_off);
		}
		else
			addFavBtn.setImageResource(R.drawable.ic_star_on);
	}

	private void updateTipsPanel() {
		tipsPanel.removeAllViews();
		List<Tips> tips=recipe.getTips();
		if(tips.size()==0)
		{
			tipsPanel.setVisibility(View.GONE);
			tipsPanelDivider.setVisibility(View.GONE);
		}
		else
		{
			tipsPanel.setVisibility(View.VISIBLE);
			tipsPanelDivider.setVisibility(View.VISIBLE);
			tipsPanel.addView(getGroupTitle("Tip:"));
			for(int i=0;i<tips.size();i++)
			{
				tipsPanel.addView(getTipsItem(tips.get(i)));
			}
		}
		
	}

	private void updateNotesPanel() {
		notesPanel.removeAllViews();
		List<Note> notes=recipe.getNotes();
		if(notes.size()==0)
		{
			notesPanel.setVisibility(View.GONE);
		}
		else
		{
			notesPanel.setVisibility(View.VISIBLE);
			for(int i=0;i<notes.size();i++)
			{
				notesPanel.addView(getNoteItem(notes.get(i)));
			}
		}
		
	}

	private void updateDirectionPanel() {
		
		directionPanel.removeAllViews();
		List<Direction> directions=recipe.getDirections();
		directionPanel.addView(getGroupTitle("Directions:"));
		for(int i=0;i<directions.size();i++)
		{
			directionPanel.addView(getDirectionItem(directions.get(i)));
		}
		
	}

	private View getTipsItem(Tips t) {
		View v=inflater.inflate(R.layout.item_direction, null);
		TextView text=(TextView)v.findViewById(R.id.content_txt);
		text.setText(t.getText());
		return v;
	}
	
	private View getNoteItem(Note n) {
		View v=inflater.inflate(R.layout.item_direction, null);
		TextView text=(TextView)v.findViewById(R.id.content_txt);
		text.setText(n.getText());
		return v;
	}
	
	private View getDirectionItem(Direction direction) {
		View v=inflater.inflate(R.layout.item_direction, null);
		TextView text=(TextView)v.findViewById(R.id.content_txt);
		text.setText(direction.getText());
		return v;
	}
	
	private View getGroupTitle(String title)
	{
		TextView groupTitle=new TextView(context);
		LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
	    llp.setMargins(10, 0, 0, 10);
	    groupTitle.setLayoutParams(llp);
		groupTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
		groupTitle.setTypeface(null, Typeface.BOLD);
		groupTitle.setText(title);
		groupTitle.setTextColor(Color.parseColor("#336600"));
		return groupTitle;
	}
	
	private void updateIngredientPanel() {
		// TODO Auto-generated method stub
		ingredientPanel.removeAllViews();
		
		List<IngGroup> groups=recipe.getIngGroups();
		for(int i=0;i<groups.size();i++)
		{
			IngGroup ingGroup=groups.get(i);
			
			ingredientPanel.addView(getGroupTitle(capitalizeFirstCharacter(ingGroup.getName())+":"));
			List<Ingredient> ingredients=groups.get(i).getIngredients();
			for(int j=0;j<ingredients.size();j++)
			{
				View v=getIngredientItem(ingredients.get(j));
				ingredientPanel.addView(v);
			}
			
			if(i+1!=groups.size())
			{
				ingredientPanel.addView(addSomeSpace());
			}
		}
	}

	
	
	private View addSomeSpace() {
		// TODO Auto-generated method stub
		View v=new View(context);
		LinearLayout.LayoutParams blankSpaceParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 10);
		v.setLayoutParams(blankSpaceParam);
		return v;
		
	}

	private View getIngredientItem(Ingredient ingredient) {
		View v=inflater.inflate(R.layout.item_ingredient, null);
		TextView text=(TextView)v.findViewById(R.id.content_txt);
		text.setText(ingredient.getText());
		return v;
	}

	private String capitalizeFirstCharacter(String input)
	{
		return input.substring(0,1).toUpperCase() +input.substring(1);
	}
	
	private String substructDotPng(String imgPathThumnail) {
		// TODO Auto-generated method stub
		
		return imgPathThumnail.replace(".png", "");
	}
	
	private void getRecipeFromDb() {
		recipe=DataBaseManager.getInstance().getRecipeDetailsByDeep(recipeId);
		DataBaseManager.getInstance().closeDb();
	}

	@Override
	public void onClick(View v) {
		if(v==addFavBtn)
		{
			updateFav();
		}
		else if(v==addToCartBtn)
		{
			Intent intent=new Intent(RecipeDetailsActivity.this,AddToCartActivity.class);
			intent.putExtra("RECIPE_ID", recipeId);
			startActivity(intent);
		}
		else if(v==addNotesBtn)
		{
			final EditText input = new EditText(this);
			
			new AlertDialog.Builder(RecipeDetailsActivity.this)
		    .setTitle("Add Note")
		    .setView(input)
		    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int whichButton) {
		            String value = input.getText().toString().trim();
		            if(!TextUtils.isEmpty(value))
		            	addNoteToDb(value);
		        }

		    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int whichButton) {
		            // Do nothing.
		        }
		    }).show();
		}
		/*else if(v==pdfBtn)
		{
			String path;
			try {
				path = AppUtility.CopyPdfToSdCard(context);
				openPdfIntent(path);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}*/
	}

	private void addNoteToDb(String value) {
		// TODO Auto-generated method stub
		noteToInsert=value;
		Thread thread = new Thread(null, addNoteThread, "MagentoBackground");
		thread.start();
		m_ProgressDialog = ProgressDialog.show(this, "", "Adding note...",
				true);
		m_ProgressDialog.setCancelable(true);
	}
	
	
	
	Runnable addNoteThread = new Runnable() {

		@Override
		public void run() {
			
			DataBaseManager.getInstance().addNotes(noteToInsert,recipeId);
			runOnUiThread(returnNoteData);
		}

		
	};
	
	Runnable returnNoteData = new Runnable() {

		@Override
		public void run() {
			m_ProgressDialog.dismiss();
			fetchRecipeDataByDeep();
		}
};
	
	
	
	
	private void updateFav() {
		Thread thread = new Thread(null, updateFavThread, "MagentoBackground");
		thread.start();
		m_ProgressDialog = ProgressDialog.show(this, "", "Updating data...",
				true);
		m_ProgressDialog.setCancelable(true);
	}
	
	Runnable updateFavThread = new Runnable() {

		@Override
		public void run() {
			favValue=recipe.getIsFav();
			if(recipe.getIsFav()==0)
			{
				favValue=1;
			}
			else
				favValue=0;
			DataBaseManager.getInstance().updateFav(favValue, recipeId);
			DataBaseManager.getInstance().closeDb();
			runOnUiThread(returnFavData);
		}

		
	};
	private void updateRecipeObject(int i) {
		recipe.setIsFav(i);
	}
	Runnable returnFavData = new Runnable() {

		@Override
		public void run() {
			m_ProgressDialog.dismiss();
			updateRecipeObject(favValue);
			updateFavBtnState(favValue);
		}

		

		
	};
	
}
